﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using System.Drawing;
using WindowsLive.Writer.Api;

namespace ClipboardLivePlugin
{
    [WriterPlugin("88E3266B-6443-44e1-B676-FD0DBCB5EF40", 
       "Clipboard Live",
       PublisherUrl = "http://codewordhank.com",
       Description = "Clipboard Live Plugin - The smart clipboard paster.",
       ImagePath = "clipboardLive.png",
       Name = "Clipboard Live",
       HasEditableOptions = true
       )]
    
    [WindowsLive.Writer.Api.InsertableContentSource("Cliboard Live", SidebarText = "Clipboard Live")]
    
    public class ClipboardLive : WindowsLive.Writer.Api.ContentSource
    {

        #region CreateContent
        // Override of CreatContent per Windows Live Writer API
        public override System.Windows.Forms.DialogResult CreateContent(System.Windows.Forms.IWin32Window dialogOwner, ref string content)
        {
            
            // Get the data out of the clipboard
            IDataObject data = new DataObject();
            data = Clipboard.GetDataObject();

            // Sometimes data can be multiple types.  Get all types supported listed in variables.
            bool isBitmap = data.GetDataPresent(DataFormats.Bitmap);
            bool isRtf = data.GetDataPresent(DataFormats.Rtf);
            bool isHtml = data.GetDataPresent(DataFormats.Html);
            bool isText = data.GetDataPresent(DataFormats.Text);
            bool isStringFormat = data.GetDataPresent(DataFormats.StringFormat); 
            bool isCsv = data.GetDataPresent(DataFormats.CommaSeparatedValue);

            // Do processing of data.  It's important to do the processing in order to fit in all options.

            #region Images
            // Image data first.
            if (isBitmap)
            {
                int imageOption = options.GetInt("ImageOption", 1);
                if (isHtml)
                {
                    try
                    {
                        // Choose to either save local file or link to http image.
                        if (imageOption == -1)
                        {
                            ImageOptionForm ioptions = new ImageOptionForm();
                            imageOption = ioptions.RunImangeOptionForm();
                            if (imageOption == -1)
                                return DialogResult.Cancel;
                        }

                        // Link to http image.  Bitmap has to be a image and part of html.
                        if (imageOption == 2)
                        {
                            CLHtmlFragment html = CLHtmlFragment.FromClipboard();
                            content = html.SpecialFragment(FragmentType.ImgParsedToHttp);
                            return DialogResult.OK;
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("There is a problem with converting the Images in the clipboard.  Clipboard Live either doesn't support this content or has encountered an internal error.  Please visit http://www.codewordhank.com for support.", "Clipboard Live Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return DialogResult.Cancel;
                    }
                }
                
                // Save image locally and show it as an img.
                if (imageOption == 1)
                {
                    try
                    {
                        Bitmap screenCapture = (Bitmap)data.GetData(DataFormats.Bitmap);

                        ImageClass imgProc = new ImageClass();
                        string jpegDir = imgProc.GetTempJpegDirectory();
                        if (File.Exists(jpegDir))
                            return DialogResult.Cancel;

                        // We ae going to convert the image at 100% of original for right now.
                        //  Why 100?  Who knows; guess I'm a perfectionist.  
                        //  TODO: Put the quality they want the jpeg converted to into options.
                        imgProc.saveBitmapAsJpeg(jpegDir, screenCapture, 100);
                        content = @"<img src=""" + jpegDir + @""" />";
                        return DialogResult.OK;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("There is a problem with converting the Images in the clipboard.  Clipboard Live either doesn't support this content or has encountered an internal error.  Please visit http://www.codewordhank.com for support.", "Clipboard Live Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return DialogResult.Cancel;
                    }
                }
                
                // should never get here
                return DialogResult.Cancel;
            }
            #endregion

            #region RTF
            // Rtf but not HTML.  If it's HTML, it's better to go through the Fragment code.
            // TODO: Can't convert images yet.  Need to look into that.
            if ((isRtf) && (!isHtml))
            {
                int rtfOption = options.GetInt("RtfOption", 1);

                // Choose to either show with formatting or without
                if (rtfOption == -1)
                {
                    RtfOptionForm roptions = new RtfOptionForm();
                    rtfOption = roptions.RunRtfOptionForm();
                    if (rtfOption == -1)
                        return DialogResult.Cancel;
                }

                try
                {
                    // Convert Rtf to HTML and return the HTML
                    if (rtfOption == 1)
                    {
                        string textFromCB = (string)data.GetData(DataFormats.Rtf);

                        HtmlRichTextBox txtBox = new HtmlRichTextBox();
                        txtBox.Rtf = textFromCB;

                        string html = txtBox.GetHTML(true, true);
                        content = html;
                        return DialogResult.OK;
                    }

                    // Strip out all escape characters and return just the text.
                    if (rtfOption == 2)
                    {
                        string textFromCB = (string)data.GetData(DataFormats.Rtf);

                        HtmlRichTextBox txtBox = new HtmlRichTextBox();
                        txtBox.Rtf = textFromCB;

                        string text = txtBox.Text;
                        content = text;
                        return DialogResult.OK;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("There is a problem with converting the RTF in the clipboard.  Clipboard Live either doesn't support this content or has encountered an internal error.  Please visit http://www.codewordhank.com for support.", "Clipboard Live Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return DialogResult.Cancel;
                }

            }
            #endregion

            #region HTML
            // Html.  Return just the fragment selected and replace images the way options specify.
            if (isHtml)
            {
                int htmlOption = options.GetInt("HtmlOption", 1);

                // Choose to either show with formatting or without
                if (htmlOption == -1)
                {
                    HtmlOptionForm hoptions = new HtmlOptionForm();
                    htmlOption = hoptions.RunHtmlOptionForm();
                    if (htmlOption == -1)
                        return DialogResult.Cancel;
                }

                try
                {
                    // Html with Images as Http
                    if (htmlOption == 1)
                    {
                        CLHtmlFragment html = CLHtmlFragment.FromClipboard();
                        content = html.SpecialFragment(FragmentType.ImgParsedToHttp);
                        return DialogResult.OK;
                    }

                    // Html with Images as Local Files
                    if (htmlOption == 2)
                    {
                        CLHtmlFragment html = CLHtmlFragment.FromClipboard();
                        content = html.SpecialFragment(FragmentType.ImgParsedToLocalFile);
                        return DialogResult.OK;
                    }

                    // Strip out all tags and return just text
                    if (htmlOption == 3)
                    {
                        CLHtmlFragment html = CLHtmlFragment.FromClipboard();
                        content = html.SpecialFragment(FragmentType.ParseAsText);
                        return DialogResult.OK;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("There is a problem with converting the HTML in the clipboard.  Clipboard Live either doesn't support this content or has encountered an internal error.  Please visit http://www.codewordhank.com for support.", "Clipboard Live Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return DialogResult.Cancel;
                }
            }
            #endregion

            #region Text
            // Some kind of Text.  No options, just paste this stuff into Writer.
            // TODO: If it's CSV, put it into a nice html table.
            if (isText || isStringFormat || isCsv)
            {
                try
                {
                    string textFromCB = data.GetData(DataFormats.Text).ToString();
                    content = textFromCB;
                    return DialogResult.OK;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("There is a problem with converting the TEXT in the clipboard.  Clipboard Live either doesn't support this content or has encountered an internal error.  Please visit http://www.codewordhank.com for support.", "Clipboard Live Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return DialogResult.Cancel;
                }
            }
            #endregion

            MessageBox.Show("The clipboard content is not recognized and cannot be pasted using this plugin.", "Clipboard paste error", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return DialogResult.Cancel;
        }
        #endregion //CreateContent


        #region Options Dialog
        // Options Dialog - To Set up Options for the new Plugin
        // -------------------------------------------------------------
        private IProperties options = null;
        public override void Initialize(IProperties pluginOptions)
        {
            options = pluginOptions;
            base.Initialize(pluginOptions);
        }

        public override void EditOptions(IWin32Window dialogOwner)
        {
            OptionsForm of = new OptionsForm(options);
            of.Show();
        }
        #endregion

    }
}
